package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.ITcpClient;
import com.fingard.net.TcpPortClient;
import com.fingard.net.TcpReceiver;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.util.secret.salary.FieldHiddenUtil;
import com.fingard.xml.XmlTextWriter;
import com.yeepay.g3.sdk.yop.utils.Exceptions;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ABC02Base extends DirectBase implements ITcpClient {
    protected static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected static final String INSERTSEQ = "INSERT INTO REQSEQIDMAPPING(URID,BANKCODE,TRANSDATE,REQSEQID,BANKREQSEQID) values (?,?,?,?,?);";
    protected static final String SELECTSEQ = "SELECT BANKREQSEQID,TRANSDATE FROM REQSEQIDMAPPING WHERE REQSEQID=? AND BANKCODE=?;";

    public static int getCharacterPosition(String string, int index){
	    //这里是获取"|"符号的位置
	    Matcher slashMatcher = Pattern.compile("\\|").matcher(string);
	    int mIdx = 0;
	    while(slashMatcher.find()) {
	       mIdx++;
	       //当"|"符号第N次出现的位置
	       if(mIdx == index){
	          break;
	       }
	    }
	    return slashMatcher.start();
	}
    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime17SSSFormat.format(tmpDateNow);
    }


    protected String getReqID(){
         Date tmpDateNow = new Date();
        return Format.DateTime14Format.format(tmpDateNow)+idHelper.getNextIDStr();
    }

    public static List<String> getResult(String str) throws Exception {
		List<String> list = new ArrayList<String>();
		for(int i = 1;i<str.length();i++) {
			int index = getCharacterPosition(str,13);
			String firstMsg = str.substring(0, index);
			list.add(firstMsg);
			str = str.substring(index+1);
		}
		return list;
	}

    protected String getCharset() {
        return getBankConfig().getCharset("GBK");
    }

    protected String getCharset(String p_def, String p_for){
		return getBankConfig().getCharset(p_def, p_for);
	}

    protected void writeCommonHeader(XmlTextWriter xmlWriter, ABC02Header p_bankHeader) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.CCTransCode)) {
            throw new Exception("未赋值CCTransCode");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.ReqSeqNo)) {
            throw new Exception("未赋值ReqSeqNo");
        }
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartElement("ap");
        if("C410".equals(p_bankHeader.CCTransCode) || "1972".equals(p_bankHeader.CCTransCode)){
            xmlWriter.writeElementString("TransCode", p_bankHeader.CCTransCode);
        }else{
            xmlWriter.writeElementString("CCTransCode", p_bankHeader.CCTransCode);
        }
        xmlWriter.writeElementString("ProductID", "ICC");
        xmlWriter.writeElementString("ChannelType", "ERP");
        xmlWriter.writeElementString("CorpNo", bankFront.org);//企业技监局号码/客户号
        xmlWriter.writeElementString("OpNo", bankFront.operator);//企业操作员编号
        xmlWriter.writeElementString("AuthNo","");
        xmlWriter.writeElementString("ReqSeqNo", p_bankHeader.ReqSeqNo);
        if (p_bankHeader.ReqDateTime == null) {
            p_bankHeader.ReqDateTime = new Date();
        }
        xmlWriter.writeElementString("ReqDate", Format.Date8Format.format(p_bankHeader.ReqDateTime));
        xmlWriter.writeElementString("ReqTime", Format.Time6Format.format(p_bankHeader.ReqDateTime));
        xmlWriter.writeElementClosed("Sign");
    }


    protected String[] sendToBank(String p_reqStr) throws Exception {
        return sendToBank(p_reqStr, "", "");
    }
    protected String[] sendToBank(String p_reqStr, String transType, String commandCode) throws Exception {

        String[] retStr = new String[]{"", ""};
        if(StringHelper.hasAnyChar(transType) && StringHelper.hasAnyChar(commandCode)) {
            this.detailSimulateForBank(bankFront.bankCode, transType, commandCode, p_reqStr, retStr);
            if (retStr[1].length() > 0) {
                return retStr;
            }
        }
        //if(bankFront.org == null || bankFront.org.length() == 0){
        //	throw new Exception("CIS不能为空");
        //}

        WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);


        //发送银行前置
        TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
        String tmpCharset = getCharset();
        byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);
        String tmpHead = "0" + String.format("%-6d", tmpBytesBody.length);
        byte[] tmpBytesHead = tmpHead.getBytes(tmpCharset);

        byte[] tmpBytesSend = new byte[tmpBytesHead.length + tmpBytesBody.length];
        System.arraycopy(tmpBytesHead, 0, tmpBytesSend, 0, tmpBytesHead.length);
        System.arraycopy(tmpBytesBody, 0, tmpBytesSend, tmpBytesHead.length, tmpBytesBody.length);

//        WriteBankLogStep2(tmpHead + p_reqStr);
        if(isNeedHiddleField){
            WriteBankLogStep2(FieldHiddenUtil.amountHiddle(tmpHead + p_reqStr,new String[]{"Amt","批交易总金额"}));
        }else{
            WriteBankLogStep2(tmpHead + p_reqStr);
        }
        TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesSend);
        if (StringHelper.isNullOrEmpty(tmpReceiver.connState)) {
            String tmpBkStr = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
//            WriteBankLogStep3(tmpBkStr);
            if(isNeedHiddleField){
                WriteBankLogStep3(FieldHiddenUtil.amountHiddle(tmpBkStr,new String[]{"成功金额","失败金额","异常金额","落地金额"}));
            }else{
                WriteBankLogStep3(tmpBkStr);
            }
        }
        retStr[0] = tmpReceiver.connState;
        if (tmpReceiver.isCompleted) {
            retStr[1] = new String(tmpReceiver.recBytes, tmpReceiver.contentStartIndex, tmpReceiver.contentLength, tmpCharset);
        } else {
            retStr[1] = tmpReceiver.getConnMsg();
            WriteBankLogLn(retStr[1]);
        }
        return retStr;
    }

    @Override
    public void getContentLength(TcpReceiver p_receiver) throws Exception {
        if (p_receiver.contentLength == -1) {
            if (p_receiver.readedLength >= 7) {
                //String tmpStrReq = new String(tmpReceiver.reqBytes,tmpReceiver.contentStartIndex,tmpReceiver.contentLength,tmpReceiver.charsetName);
                String tmpHead = new String(p_receiver.recBytes, 1, 6, getCharset());
                p_receiver.contentLength = Integer.parseInt(tmpHead.trim());
                p_receiver.contentStartIndex = 7;
            }
        }
    }

    public String getAbcAccNo(String p_actNum) {
        //         2省市(-)15账号或者15账号-2省市
        if ((p_actNum.indexOf('-') == 2 && p_actNum.length() == 18) || (p_actNum.length() == 17)) {
            return p_actNum.substring(p_actNum.length() - 15);
        } else if(p_actNum.indexOf('-') ==15 && p_actNum.length() == 18) {
            return p_actNum.substring(0,15);
        }
        //考虑多级账簿的情况   2省市(-)15账号10账薄
        else if((p_actNum.indexOf('-') == 2 && p_actNum.length() == 28) || (p_actNum.length() == 27)){
            return p_actNum.substring(p_actNum.length() - 25,p_actNum.length() - 10);
        }
        //考虑子账户是二级账簿的情况    2省市15账号-10账薄
        else if(p_actNum.indexOf('-') ==17 && p_actNum.length() == 28) {
            return p_actNum.substring(2,17);
        }
//        15账号10账薄
        else if( p_actNum.length() == 25) {
            return p_actNum.substring(0,15);
        }
        return p_actNum;
    }

    public String getAbcLogAccNo(String p_actNum) {

        //考虑多级账簿的情况
         if((p_actNum.indexOf('-') == 2 && p_actNum.length() == 28) || (p_actNum.length() == 27)){
            return p_actNum.substring(p_actNum.length() - 10);
        }
         //考虑子账户是二级账簿的情况    2省市15账号-10账薄
         else if(p_actNum.indexOf('-') == 17 && p_actNum.length() == 28){
             return p_actNum.substring(18);
         }
         else if(p_actNum.indexOf('-') ==25 && p_actNum.length() == 28) {
            return p_actNum.substring(15,25);
        }else if( p_actNum.length() == 25) {
             return p_actNum.substring(15);
         }
        return "";
    }



    public String getAbcAccProv(String p_actNum,String area) throws Exception{
        if ((p_actNum.indexOf('-') == 2 && p_actNum.length() == 18) || (p_actNum.length() == 17)) {
            return p_actNum.substring(0,2);
        } else if(p_actNum.indexOf('-') ==15 && p_actNum.length() == 18) {
            return p_actNum.substring(16);
        }
        //考虑多级账簿的情况
        else if((p_actNum.indexOf('-') == 2 && p_actNum.length() == 28) || (p_actNum.length() == 27)){
            return p_actNum.substring(0,2);
        }
        //考虑子账户是二级账簿的情况    2省市15账号-10账薄
        else if((p_actNum.indexOf('-') == 17 && p_actNum.length() == 28)){
            return p_actNum.substring(0,2);
        }
        else if(p_actNum.indexOf('-') ==25 && p_actNum.length() == 28) {
            return p_actNum.substring(26);
        }
        if(StringHelper.hasAnyChar(area)&&area.length()==2){
            return area;
        }
        throw new Exception("根据银行账户：["+p_actNum+"]和地区码：["+area+"]获取直联省市失败");
    }

    public String getAbcAccNoWithCode(String p_actNum, String areaCode) {

        if (p_actNum.length() == 17) {
            p_actNum = p_actNum.substring(0, 2) + "-" + p_actNum.substring(2);
        } else if (p_actNum.length() == 15) {
            p_actNum = areaCode.substring(0, 2) + "-" + p_actNum;
        }
        return p_actNum;
    }

    /**
     * 根据截止日期和期限，计算开始日期
     * @param endDate
     * @param terms
     * 存款期限 (七天`1,一个月`2,三个月`3,六个月`4,一年`5,二年`6,三年`7,五年`8,其它`9)
     * @return
     */
    protected String[] getStartDateByEndDateAndTerm(String endDate,String terms) throws Exception{
        String[] result=new String[]{"9",""};
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(Format.Date8Format.parse(endDate));
        if("D001".equals(terms)){
            result[0]="9";
            calendar.add(Calendar.DATE,-1);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("D007".equals(terms)){
            result[0]="1";
            calendar.add(Calendar.DATE,-7);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("M003".equals(terms)){
            result[0]="3";
            calendar.add(Calendar.MONTH,-3);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("M006".equals(terms)){
            result[0]="4";
            calendar.add(Calendar.MONTH,-6);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("Y001".equals(terms)){
            result[0]="5";
            calendar.add(Calendar.YEAR,-1);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("Y002".equals(terms)){
            result[0]="6";
            calendar.add(Calendar.YEAR,-2);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("Y003".equals(terms)){
            result[0]="7";
            calendar.add(Calendar.YEAR,-3);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("Y005".equals(terms)){
            result[0]="8";
            calendar.add(Calendar.YEAR,-5);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }else if("Y008".equals(terms)){
            result[0]="9";
            calendar.add(Calendar.YEAR,-8);
            result[1]=Format.Date10Format.format(calendar.getTime());
        }
        return result;
    }
	protected  String[] sendToATS(String jsonData) throws Exception{
		String[] retStr = new String[]{"",""};
		WriteBankLogLn("2.提交ATS的地址："+ FGBiz.dspCenter.dspSet.receiptPushServerUrl);

		//发送ATS
		WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
		tmpRequest.setConnectTimeout(60000);
		tmpRequest.setRequestProperty("connection", "Close");
		tmpRequest.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		String charsetName = getCharset();
		WriteBankLogLn("3.推送给ATS的json数据"+jsonData);
		byte[] tmpWriteBytes = jsonData.getBytes(charsetName);
		retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
		WriteBankLogLn("4.返回的数据"+retStr[1]);

		return retStr;
	}

	protected static boolean compareTime(String time,int hours) throws ParseException {
        boolean flag = false;
        if(StringHelper.hasAnyChar(time)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = sdf.parse(time);
            long oldTime = date.getTime();
            long nowTime = System.currentTimeMillis();
            if((oldTime + hours*60*60*1000)<nowTime){
                flag = true;
            }
        }
        return flag;
    }

    protected static boolean isActiveRetCode(String retCode) {
        if (retCode != null) {
            if (retCode.equals("0000")) {
                return true;
            }
        }
        return false;
    }
}
